<?php

namespace app\common\helper;

use app\common\model\ExpressOrder;
use app\common\model\ExpressOrderLog;
use GuzzleHttp\Client;
use think\Exception;
use think\exception\HttpResponseException;
use think\helper\Str;

class ExpressHelper
{
    protected $callbackUrl;
    protected $key;
    public function __construct() {
        $config = cache('config');
        $this->key = $config['express_key'];
        $this->callbackUrl = request()->domain()."/api/express/callback";
    }
    public function subScribe($express_code ,$express_no,$phone = null)
    {
        //请求参数
        $post_data = array();
        $post_data["schema"] = 'json';
        $post_data["param"] = [
            'company' => $express_code,//快递公司编码
            'number' => $express_no,//快递单号
            'key' => $this->key,
            'parameters' => [
                'callbackurl' => $this->callbackUrl,//回调地址
                'salt' => Str::random(10),
                'resultv2' => '1',//行政区域解析
                'autoCom' => '0',//单号智能识别
                'phone' => $phone
            ]
        ];
        $url = 'http://poll.kuaidi100.com/poll';    //订阅请求地址
        $post_data["param"] = json_encode($post_data["param"]);
        $params = "";
        foreach ($post_data as $k=>$v) {
            $params .= "$k=".urlencode($v)."&";     //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
    
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        return json_decode($result,true);
    }
    
    public function callback($post)
    {
        //设置过滤方法
        if (request()->isPost()) {
            $log = new ExpressOrderLog();
            // 接收消息
            try {
                $param = json_decode($post["param"], true);
                $status = $param['status']; // 状态 polling:监控中，shutdown:结束，abort:中止，updateall：重新推送
                $message = $param['lastResult']['message']; // 消息体
                $state = $param['lastResult']['state']; // 快递单当前状态，包括0在途，1揽收，2疑难，3签收，4退签，5派件，6退回，7转投
                $ischeck = $param['lastResult']['ischeck']; // 是否签收标记
                $nu = $param['lastResult']['nu']; // 快递单号
                $com = $param['lastResult']['com']; // 快递公司编码
                $data = $param['lastResult']['data']; // 数组，包含多个对象，每个对象字段如展开所示
                // 查询快递是否存在
                $express = $log->where(['express_no' => $nu])->find();
                if($express){
                    if ($ischeck) {
                        $order = ExpressOrder::where("express_no",$nu)->find();
                        if ($order) {
                            $order->status = 2;
                            $order->save();
                        }
                    }
                    $express->sign = $post['sign'];
                    $express->message = $message;
                    $express->status = $status;
                    $express->state = $state;
                    $express->ischeck = $ischeck;
                    $express->com = $com;
                    $express->info = $data;
                    $express->save();
                    // 判断更新状态
                    throw new HttpResponseException(json(["result" => true, "returnCode" => "200", "message" => "接收成功"]));
                }else{
                    $log->save([
                        "message" => $message,
                        "status" => $status,
                        "state" => $state,
                        "ischeck" => $ischeck,
                        "express_no" => $nu,
                        "com" => $com,
                        "info" => $data,
                        "sign" => $post['sign']
                    ]);
                    throw new HttpResponseException(json(["result" => true, "returnCode" => "200", "message" => "接收成功"]));
                }
            } catch (Exception $e) {
                writeLog($e->getMessage());
                throw new HttpResponseException(json(["result" => false, "returnCode" => "500", "message" => "错误"]));
            }
        }
        throw new HttpResponseException(json(["result" => false, "returnCode" => "500", "message" => "非正常访问"]));
    }
}